<template>
  <div id="app">
    <Header :title="title"></Header>
    <!--  表单  -->
    <van-form @submit="onSubmit">
      <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
          v-model="password2"
          type="password"
          name="密码2"
          label="密码2"
          placeholder="密码2"
          :rules="[{ validator, message: '请输入相同的密码' }]"
      />
      <div style="margin: 16px;">
        <van-button square block type="primary" native-type="submit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Header from '../components/Header'
import {Dialog} from "vant";
import {registerUser} from '../utils/api'
export default {
  name: "Register",
  components:{
    Header
  },
  data(){
    return {
      title: '注册',
      username: '',
      password: '',
      password2: '',
    }
  },
  methods: {
    async onSubmit(values) {
      const res = await registerUser(values.username,values.password)
      console.log(res)

      if(res.code === 100){
        return this.success()
      }else{
        return this.fail(res.message)
      }

    },
    validator(value){
       return value === this.password ? true : false
    },
    success(){
      Dialog.alert({
        title: '消息',
        message: '注册成功',
        theme: 'round-button',
      }).then(() => {
        // on close
      });
    },
    fail(message){
      Dialog.alert({
        title: '消息',
        message: message,
        theme: 'round-button',
      }).then(() => {
        // on close
      });
    }
  },
}
</script>

<style scoped>

</style>